package com.test.servicedemo;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.Nullable;

public class MyService extends Service {

    private int count;

    private boolean quit;

    private MyBinder binder = new MyBinder();

    private static final String TAG = "htz_test";
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.e(TAG, "onBind: " + "service is Binded" );
        return binder;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.e(TAG, "onUnbind: " + "service is Unbinded" );
        return true;
    }

    @Override
    public void onCreate() {
        Log.e(TAG, "onCreate: " + "service创建" );
        super.onCreate();
        new Thread(() -> {
            while (!quit){
                try {
                    Thread.sleep(1000);
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
                MyService.this.count++;
            }
        }).start();
    }

    //service被启动是回调该方法
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e(TAG, "onStartCommand: " + "service start" );
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        Log.e(TAG, "onDestroy: " + "service 销毁" );
        super.onDestroy();
        this.quit = true;
    }

    class MyBinder extends Binder{
        public int getCount(){
            return  MyService.this.count;
        }
    }
}
